package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.*;
import com.baomidou.ant.mapper.CheckInfoMapper;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.vo.request.RequestCheckPassVo;
import com.baomidou.ant.vo.request.RequestListCheckInfoVo;
import com.baomidou.ant.vo.response.ResponseCheckInfoVo;
import com.baomidou.ant.vo.response.ResponseListCheckInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class CheckInfoServiceImpl extends ServiceImpl<CheckInfoMapper, CheckInfo> implements ICheckInfoService {
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IReportOrderService reportOrderService;
    @Autowired
    private IProcessInfoService processInfoService;
    @Autowired
    private IParentOrderService parentOrderService;

    @Override
    public boolean checkPass(RequestCheckPassVo vo) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(vo.getOrderNum());
        if(Objects.equals(workOrder.getOrderStatus(), "2")){
            return false;
        }
        workOrder.setOrderStatus("2");
        if(workOrderService.updateById(workOrder)){
            CheckInfo checkInfo=new CheckInfo();
            checkInfo.setOrderNum(vo.getOrderNum());
            SysUser user=userService.queryByLoginName(vo.getLoginName());
            checkInfo.setChecker(user.getUserName());
            checkInfo.setCheckerNo(user.getLoginName());
            checkInfo.setPass(Objects.equals(vo.getPassStatus(), "1"));
            //判断父工单
            ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
            QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("parent_id",workOrder.getParentId());
            List<WorkOrder> allChildList=workOrderService.list(queryWrapper);
            queryWrapper.eq("order_status",workOrder.getOrderStatus());
            List<WorkOrder> allOverChild=workOrderService.list(queryWrapper);
            if(allChildList.size()==allOverChild.size()){//所有子工单都完结了
                parentOrder.setOver(true);
                parentOrderService.updateById(parentOrder);
            }
            return save(checkInfo);
        }else
            return false;
    }

    @Override
    public IPage<ResponseListCheckInfoVo> listCheck(RequestListCheckInfoVo requestListCheckInfoVo) {
        SysUser sysUser=userService.queryByLoginName(requestListCheckInfoVo.getCheckerNo());
        IPage<CheckInfo> infoIPage=new Page<>(requestListCheckInfoVo.getDisplayStart(),requestListCheckInfoVo.getDisplayLength());
        QueryWrapper<CheckInfo> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(requestListCheckInfoVo.getOrderNum())){
            queryWrapper.like("order_num",requestListCheckInfoVo.getOrderNum());
        }
        if(StringUtils.isNotBlank(requestListCheckInfoVo.getCheckStatus())){
            queryWrapper.eq("is_pass",requestListCheckInfoVo.getCheckStatus());
        }
        if(StringUtils.isNotBlank(requestListCheckInfoVo.getChecker())){
            queryWrapper.like("checker",requestListCheckInfoVo.getChecker());
        }
        //自己的审核记录,不是管理员,则只能看到自己的
        if(!Objects.equals(sysUser.getType(), "1")){
            queryWrapper.eq("checker_no",requestListCheckInfoVo.getCheckerNo());
        }
        //时间排序
        if(Objects.equals(requestListCheckInfoVo.getDesc(), "desc")|| ObjectUtils.isEmpty(requestListCheckInfoVo.getDesc())){
            queryWrapper.orderByDesc("create_time");
        }
        if(Objects.equals(requestListCheckInfoVo.getDesc(), "asc")){
            queryWrapper.orderByAsc("create_time");
        }
        int allTotal=list(queryWrapper).size();
        IPage<CheckInfo> page= page(infoIPage,queryWrapper);
        return page.convert(checkInfo -> {
            ResponseListCheckInfoVo responseListCheckInfoVo=new ResponseListCheckInfoVo();
            BeanUtils.copyProperties(checkInfo,responseListCheckInfoVo);
            responseListCheckInfoVo.setAllTotal(allTotal);
            return responseListCheckInfoVo;
        });
    }

    @Override
    public CheckInfo queryByOrderNum(String orderNum) {
        QueryWrapper<CheckInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",orderNum);
        return list(queryWrapper).get(0);
    }

    @Override
    public ResponseCheckInfoVo getCheckInfo(String orderNum) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(orderNum);
        ResponseCheckInfoVo vo=new ResponseCheckInfoVo();
        //得到相关的工序和执行人
        int[] processIds= MyStringUtil.toInt(workOrder.getProcess());
        List<String> processList=new ArrayList<>();
        for(int i:processIds){
            if(i==0){
                continue;
            }
            ProcessInfo processInfo=processInfoService.getById(i);
            processList.add(processInfo.getProcessName());
        }
        StringBuilder processResult= new StringBuilder();
        for(String str:processList){
            processResult.append(str).append(";");
        }
        vo.setProcess(processResult.toString());
        vo.setOrderNum(orderNum);
        vo.setAmount(workOrder.getAmount());
        vo.setAmountPlan(workOrder.getAmountPlan());
        int badAmount=0;
        int missingAmount=0;
        StringBuilder workerResult= new StringBuilder();
        List<ReportOrder> reportOrderList=reportOrderService.queryByOrderNum(orderNum);
        for(ReportOrder reportOrder:reportOrderList){
            badAmount+=reportOrder.getBadAmount();
            missingAmount+=reportOrder.getMissingAmount();
            workerResult.append(reportOrder.getProcessWorker()).append(";");
        }
        vo.setWorkers(workerResult.toString());
        vo.setBadAmount(badAmount);
        if(missingAmount==(workOrder.getAmountPlan()-workOrder.getAmount()-badAmount)){
            vo.setMissingAmount(missingAmount);
        }else
            vo.setMissingAmount(workOrder.getAmountPlan()-workOrder.getAmount()-badAmount);
        CheckInfo checkInfo=queryByOrderNum(orderNum);
        vo.setChecker(checkInfo.getChecker());
        vo.setNgReason(checkInfo.getNgReason());
        vo.setCreateTime(checkInfo.getCreateTime());
        if(checkInfo.isPass()){
            vo.setResult("已通过");
        }else
            vo.setResult("未通过");
        return vo;
    }
}
